package C058;

import java.util.Arrays;

/**
 * ClassName: c04
 * Package: C058
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/5/3 19:54
 * @Version 1.0
 * @Since 1.0
 */
public class c04 {
    public static void main(String[] args) {
        int[][] arr = {{1,0,0,0},{1,1,1,0}};
        int[][] arr2 = {{1,0}};
        System.out.println(Arrays.toString(hitBricks(arr, arr2)));
    }

    static int[][] g, h;

    public static int[] hitBricks(int[][] grid, int[][] hits) {
        g = grid;
        h = hits;

        // 打击点 -1
        for (int i = 0; i < hits.length; i++) {
            grid[hits[i][0]][hits[i][1]] --;
        }

        // 顶部dfs
        for (int i = 0; i < g[0].length; i++) {
            dfs(0, i);
        }

        // 时光倒流
        int[] ans = new int[h.length];
        for (int i = h.length - 1; i >= 0; i--) {
            g[h[i][0]][h[i][1]] ++;
            if(worth(i)) {
                ans[i] = dfs(h[i][0], h[i][1]) - 1;
            }
        }
        return ans;
    }

    private static boolean worth(int i) {
        int row = h[i][0];
        int col = h[i][1];
        return g[row][col] == 1  && (
                row == 0
                || (row > 0 && g[row - 1][col] == 2)
                || (row < g.length - 1 && g[row + 1][col] == 2)
                || (col > 0 && g[row][col - 1] == 2)
                || (col < g[0].length - 1 && g[row][col + 1] == 2));
    }

    private static int dfs(int i, int j) {
        if(i == -1 || i == g.length || j == -1 || j == g[0].length || g[i][j] != 1) {
            return 0;
        }
        g[i][j] = 2;
        return 1 +
        dfs(i - 1, j) +
        dfs(i + 1, j) +
        dfs(i, j - 1) +
        dfs(i, j + 1);
    }
}
